﻿using Rougamo;
using Rougamo.Context;

/// <summary>
/// 
/// </summary>

[AttributeUsage(AttributeTargets.Method)]
public class CacheDeleteTenantAttribute : MoAttribute
{
    /// <summary>
    /// 类型 注意类型和方法的顺序要一致数量要相等
    /// </summary>
    public Type[] Types { get; set; }

    /// <summary>
    /// 方法（注意类型和方法的顺序要一致数量要相等）
    /// </summary>
    public string[] Methods { get; set; }
    /// <summary>
    /// 缓存
    /// </summary>
    public string CacheKey { get; set; } = "";



    /// <summary>
    /// 缓存
    /// </summary>
    /// <param name="cacheKey"></param>
    public CacheDeleteTenantAttribute(string cacheKey)
    {
        CacheKey = cacheKey;
    }


    /// <summary>
    /// 清除缓存
    /// </summary>
    /// <param name="type"></param>
    /// <param name="method"></param>
    public CacheDeleteTenantAttribute(Type type, string method)
    {
        Types = new Type[] { type };
        Methods = new string[] { method };
    }



    /// <summary>
    /// 清除数据
    /// </summary>
    /// <param name="types"></param>
    /// <param name="methods"></param>
    public CacheDeleteTenantAttribute(Type[] types, string[] methods)
    {
        Types = types;
        Methods = methods;
    }

    private ICache _cache;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public override void OnEntry(MethodContext context)
    {
        // 从context对象中能取到包括入参、类实例、方法描述等信息
        _cache = context.GetRequiredService<ICache>();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public override void OnException(MethodContext context)
    {

    }



    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public override void OnExit(MethodContext context)
    {

        if (!string.IsNullOrWhiteSpace(CacheKey))
        {

            this.CacheKey += (TenantContext.Tenant?.Identifier ?? "");
            if (CacheKey.Contains("*"))
            {
                _cache.RemoveByPatternAsync(CacheKey.Replace("*", ""));
            }
            else
            {
                _cache.Remove(CacheKey);
            }

            //logger.LogDebug($"删除缓存key：{CacheKey}*");
        }
        else
        {
            if (this.Types.Length != this.Methods.Length)
            {
                //日志记录失败    throw new Exception("Types必须跟Methods数量一致");
                //logger.LogError($"缓存清除失败：{JSON.Serialize(new { Types, Methods })}Types必须跟Methods数量一致");
            }
            for (int i = 0; i < Types.Length; i++)
            {
                var type = Types[i];
                var meth = Methods[i];
                string key = (TenantContext.Tenant?.Identifier ?? "");
                key = "Methods:" + "_" + type.FullName + "." + meth;
                // key = "Methods:" + "_" + type.FullName + "." + meth;

                //logger.LogDebug($"删除缓存主KEY{key}");
                key = MD5Encrypt.Encrypt16(key);

                //logger.LogDebug($"删除缓存key：{key}*");
                _cache.RemoveStartWithAsync(key).Wait();
            }
        }

    }
}